#include "executor/system_file_executor.h"

#include <chrono>
#include <fstream>
#include <future>
#include <iostream>
#include <sstream>
#include <thread>

#include "parser/system_file_parser.h"
#include <glog/logging.h>

namespace sysinfo {
namespace monitor {

SystemFileExecutor::SystemFileExecutor(const CommandConfigs& file_configs,
                                       BoundedMonitorQueue<SystemInfoProto>& system_info_queue)
    : file_configs_(file_configs),
      system_info_queue_(system_info_queue),
      run_ctrl_(false),
      non_reentrant_stop_(false) {
    parser_ = std::make_unique<SystemFileParser>();
    Init();
}

SystemFileExecutor::~SystemFileExecutor() {
    // 确保资源被正确释放
    if (!non_reentrant_stop_.load()) {
        Stop();
    }
}

void SystemFileExecutor::Init() {
    // 检查配置中的文件是否存在，如果不存在则从配置中剔除并记录错误日志
    auto it = file_configs_.begin();
    while (it != file_configs_.end()) {
        // 组合完整文件路径
        std::string file_path;
        if (!it->path().empty() && it->path().back() == '/') {
            file_path = it->path() + it->name();
        } else {
            file_path = it->path() + "/" + it->name();
        }

        // 检查文件是否存在
        std::ifstream file(file_path);
        if (!file.is_open()) {
            LOG(ERROR) << "System file does not exist or is not accessible: " << file_path;
            // 从配置中移除该文件
            it = file_configs_.erase(it);
        } else {
            LOG(INFO) << "System file exists: " << file_path;
            ++it;
        }
    }
}

void SystemFileExecutor::Start() {
    for (const auto& config : file_configs_) {
        // 异步执行系统文件收集任务
        auto future = std::async(std::launch::async, [this, config]() {
            while (!run_ctrl_) {
                CollectSystemFile(config);
                // 添加50ms的循环处理间隔，避免资源竞争
                std::this_thread::sleep_for(std::chrono::milliseconds(50));
            }
        });

        collection_futures_.emplace_back(std::move(future));
    }
}

void SystemFileExecutor::Stop() {
    // 检查是否已经停止过
    if (non_reentrant_stop_.load()) {
        return;
    }

    LOG(INFO) << "Stopping all file commands";
    run_ctrl_.store(true);
    non_reentrant_stop_.store(true);

    // 等待所有异步任务完成
    for (auto& future : collection_futures_) {
        if (future.valid()) {
            future.wait();
        }
    }
    collection_futures_.clear();

    LOG(INFO) << "All file commands stopped";
}

void SystemFileExecutor::CollectSystemFile(const CommandConfig& config) {
    while (!run_ctrl_.load()) {
        // std::cout << "Collecting system file: " << config.path() << std::endl;
        // 对于system_file_executor，需要组合path和name作为完整文件路径
        std::string file_path;
        if (!config.path().empty() && config.path().back() == '/') {
            file_path = config.path() + config.name();
        } else {
            file_path = config.path() + "/" + config.name();
        }
        
        std::ifstream file(file_path);
        if (!file.is_open()) {
            LOG(ERROR) << "Failed to open system file: " << file_path;
        } else {
            std::stringstream buffer;
            buffer << file.rdbuf();
            std::string content = buffer.str();

            if (!content.empty()) {
                ParseSystemFile(config, content);
            }
        }

        // 使用配置中的间隔时间，如果没有配置则默认每秒收集一次
        // 确保即使interval为0也至少等待1秒（1000毫秒）
        uint32_t interval = config.has_interval() ? (config.interval() > 0 ? config.interval() : 1000) : 1000;
        std::this_thread::sleep_for(std::chrono::milliseconds(interval));
    }
}

void SystemFileExecutor::ParseSystemFile(const CommandConfig& file_config,
                                        const std::string& output) {
    LOG(INFO) << "Processing system file: " << file_config.name();

    if (file_config.need_publish()) {
        SystemInfoProto system_info_proto;

        if (parser_ && parser_->Parse(file_config.name(), output, &system_info_proto)) {
            // SystemFileExecutor不处理oneshot任务，所有结果都放入主队列
            system_info_queue_.Put(system_info_proto);
            LOG(INFO) << "Publishing system file data to system info queue: " << file_config.name();
        } else {
            LOG(ERROR) << "Failed to parse system file: " << file_config.name();
        }
    } else {
        // 直接打印输出
        LOG(INFO) << "[DIRECT PRINT] " << file_config.name() << " >> " << output;
    }
}

}  // namespace monitor
}  // namespace sysinfo